<?php

namespace app\admin\controller;

use app\admin\model\MemberModel;
use app\admin\model\UserType;
use app\common\model\OrderModel;
use app\common\model\PayLogModel;
use app\common\model\RefundLogModel;
use think\Db;
use think\Log;
use Payment\Client\Refund;
use Payment\Config;

class Order extends Base
{
    public function index(){

    }

  public function pending(){

      $key = input('key');
      $map = ['pay_status'=>1,'ord_status'=>0];
      if($key&&$key!=="")
      {
          $map['uid|phone|out_trade_no'] = ['like',"%" . $key . "%"];
      }
      $OrderModel= new OrderModel();

      $Nowpage = input('get.page') ? input('get.page'):1;
      $limits = config('list_rows');// 获取总条数
      $count = $OrderModel->where($map)->count();//计算总页面
      $allpage = intval(ceil($count / $limits));
      $lists = $OrderModel->where($map)->page($Nowpage, $limits)->order('id desc')->select();
      $user=new MemberModel();
      foreach ($lists as $k=>$v){
          $v->nick=$user->where(['id'=>$v->uid])->value('nickname');
      }
      $this->assign('Nowpage', $Nowpage); //当前页
      $this->assign('allpage', $allpage); //总页数
      $this->assign('val', $key);
      if(input('get.page'))
      {
          return json($lists);
      }
      return $this->fetch();
  }

    public function complete(){
        $key = input('key');
        $map = ['pay_status'=>1,'ord_status'=>1];
        if($key&&$key!=="")
        {
            $map['uid|phone|out_trade_no'] = ['like',"%" . $key . "%"];
        }
        $OrderModel= new OrderModel();

        $Nowpage = input('get.page') ? input('get.page'):1;
        $limits = config('list_rows');// 获取总条数
        $count = $OrderModel->where($map)->count();//计算总页面
        $allpage = intval(ceil($count / $limits));
        $lists = $OrderModel->where($map)->page($Nowpage, $limits)->order('id desc')->select();
        $user=new MemberModel();
        foreach ($lists as $k=>$v){
            $v->nick=$user->where(['id'=>$v->uid])->value('nickname');
        }
        $this->assign('Nowpage', $Nowpage); //当前页
        $this->assign('allpage', $allpage); //总页数
        $this->assign('val', $key);
        if(input('get.page'))
        {
            return json($lists);
        }
        return $this->fetch();
    }

    public function refund(){
        $key = input('key');
        $map = ['pay_status'=>2,'ord_status'=>2];
        if($key&&$key!=="")
        {
            $map['uid|phone|out_trade_no'] = ['like',"%" . $key . "%"];
        }
        $OrderModel= new OrderModel();

        $Nowpage = input('get.page') ? input('get.page'):1;
        $limits = config('list_rows');// 获取总条数
        $count = $OrderModel->where($map)->count();//计算总页面
        $allpage = intval(ceil($count / $limits));
        $lists = $OrderModel->where($map)->page($Nowpage, $limits)->order('id desc')->select();
        $user=new MemberModel();
        foreach ($lists as $k=>$v){
            $v->nick=$user->where(['id'=>$v->uid])->value('nickname');
        }
        $this->assign('Nowpage', $Nowpage); //当前页
        $this->assign('allpage', $allpage); //总页数
        $this->assign('val', $key);
        if(input('get.page'))
        {
            return json($lists);
        }
        return $this->fetch();
    }
    public function getinfo(){
        $id=input('get.id');
        $info= OrderModel::get($id);
        return json(['code' => 1, 'data' => $info, 'msg' =>'']);
    }
    public function chongzhiok(){
        $id=input('post.id');
        $info= OrderModel::get($id);
        if($info->pay_status ==2){
            return json(['code' => 0, 'data' => '', 'msg' =>'已经退款订单无法完成']);
        }
        if($info->ord_status !=0){
            return json(['code' => 0, 'data' => '', 'msg' =>'已经处理的订单无法完成']);
        }
        $info->ord_status=1;
        if($info->save()){
            //通知用户充值OK
            //查找用户的OPENID
            $touser=db('oauth_member')->where(['mid'=>$info->uid])->value('openid');
            //微信通知 用户充值成功
            $we=new \Wechat\WechatReceive($this->wx_config);
           $we->sendTemplateMessage([
                'touser'=>$touser,
                'template_id'=>'1w8OS4FiOcI_Xi3tmKj8GiTO8uzg7t5lyqCgIgXyHW4',
                //'url'=>url('weixin/shanghu/index','',true,true),
                'data'=>[
                    'first'=>[
                        "value"=>"您好，您已成功进行话费充值。",
                        "color"=>"#173177"
                    ],
                    'accountType'=>[
                        "value"=>'手机号',
                        "color"=>"#173177"
                    ],
                    'account'=>[
                        "value"=>$info->phone,
                        "color"=>"#173177"
                    ],
                    'amount'=>[
                        "value"=>$info->order_money,
                        "color"=>"#173177"
                    ],
                    'result'=>[
                        "value"=>'充值成功',
                        "color"=>"#173177"
                    ],
                    'remark'=>[
                        "value"=>"谢谢支持，如有疑问请联系客服！",
                        "color"=>"#173177"
                    ]
                ]
            ]);

            return json(['code' =>1, 'data' => '', 'msg' =>'已处理']);
        }
    }
    public function chongzhituikuai(){
        $id=input('post.id');
        $info= OrderModel::get($id);
        if($info->pay_status ==1){
            //生成订单
            $orderNo = time() . rand(1000, 9999);
            //先判断是怎么购买的
            //然后在执行退款
            if($info->paytype==1){
            //直接支付

                RefundLogModel::create([
                    'out_trade_no'=>$orderNo,
                    'money'=>$info->reality_money,
                    'userid'=> $info->uid,
                    'rmb'=>$info->rmb,
                    'ord'=>$info->out_trade_no,
                ]);
                $data = [
                    'out_trade_no' => $info->out_trade_no,
                    'total_fee' => $info->rmb,
                    'refund_fee' =>$info->rmb,
                    'refund_no' => $orderNo,
                    'refund_account' =>'REFUND_SOURCE_UNSETTLED_FUNDS',// REFUND_RECHARGE:可用余额退款  REFUND_UNSETTLED:未结算资金退款（默认）
                ];

                try {
                    $ret = Refund::run(Config::WX_REFUND,$this->wxConfig, $data);

                } catch (PayException $e) {
                    return json(['code' => 0, 'data' => '', 'msg' =>$e->errorMessage()]);
                    echo $e->errorMessage();
                    exit;
                }
                if($ret){
                    if($info->save(['pay_status'=>2,'ord_status'=>2])&&RefundLogModel::update(['status'=>1],['out_trade_no'=>$orderNo])){

                        $touser=db('oauth_member')->where(['mid'=>$info->uid])->value('openid');
                        //微信通知 用户退款
                        $we=new \Wechat\WechatReceive($this->wx_config);
                        $we->sendTemplateMessage([
                            'touser'=>$touser,
                            'template_id'=>'-jB0hQCJFoBnAkypDO5MH6SGu_nD4MBu3uRIh1jRR48',
                            //'url'=>url('weixin/shanghu/index','',true,true),
                            'data'=>[
                                'first'=>[
                                    "value"=>"您好，非常抱歉的通知您，您提交的充值订单充值失败，我们已为您办理退款。",
                                    "color"=>"#173177"
                                ],
                                'keyword1'=>[
                                    "value"=>$info->out_trade_no,
                                    "color"=>"#173177"
                                ],
                                'keyword2'=>[
                                    "value"=>$info->phone,
                                    "color"=>"#173177"
                                ],
                                'keyword3'=>[
                                    "value"=>$info->reality_money,
                                    "color"=>"#173177"
                                ],
                                'keyword4'=>[
                                    "value"=>date('Y-m-d H:i:s'),
                                    "color"=>"#173177"
                                ],
                                'remark'=>[
                                    "value"=>"退款会根据你充值原方式返回",
                                    "color"=>"#173177"
                                ]
                            ]
                        ]);
                        return json(['code' =>1, 'data' => '', 'msg' =>'退款成功']);
                    }
                }
            }else{
                //余额支付 先给用户加钱
                if(!db('member')->where(['id'=>$info->uid])->setInc('money',$info->reality_money)){
                    Log::error(db('member')->getLastSql());
                }else{
                    //创建记录
                    PayLogModel::create([
                        'out_trade_no'=>$orderNo,
                        'money'=>$info->reality_money,//实际支付金额
                        'userid'=> $info->uid,
                        'rmb'=> $info->rmb,
                        'status'=> 1,
                        'act'=> 4,
                        'param'=> $info->out_trade_no
                    ]);
                    //改变订单状态
                   if($info->save(['pay_status'=>2,'ord_status'=>2])){
                       //查找用户的OPENID
                       $touser=db('oauth_member')->where(['mid'=>$info->uid])->value('openid');
                       //微信通知 用户退款
                       $we=new \Wechat\WechatReceive($this->wx_config);
                       $we->sendTemplateMessage([
                           'touser'=>$touser,
                           'template_id'=>'-jB0hQCJFoBnAkypDO5MH6SGu_nD4MBu3uRIh1jRR48',
                           //'url'=>url('weixin/shanghu/index','',true,true),
                           'data'=>[
                               'first'=>[
                                   "value"=>"您好，非常抱歉的通知您，您提交的充值订单充值失败，我们已为您办理退款。",
                                   "color"=>"#173177"
                               ],
                               'keyword1'=>[
                                   "value"=>$info->out_trade_no,
                                   "color"=>"#173177"
                               ],
                               'keyword2'=>[
                                   "value"=>$info->phone,
                                   "color"=>"#173177"
                               ],
                               'keyword3'=>[
                                   "value"=>$info->reality_money,
                                   "color"=>"#173177"
                               ],
                               'keyword4'=>[
                                   "value"=>date('Y-m-d H:i:s'),
                                   "color"=>"#173177"
                               ],
                               'remark'=>[
                                   "value"=>"退款会根据你充值原方式返回",
                                   "color"=>"#173177"
                               ]
                           ]
                       ]);
                       return json(['code' =>1, 'data' => '', 'msg' =>'退款成功']);
                   }
                }

            }
            //然后改变状态
        }else if ($info->pay_status ==2){
            return json(['code' => 0, 'data' => '', 'msg' =>'不能重复退款']);
        }else{
            return json(['code' => 0, 'data' => '', 'msg' =>'退款失败']);
        }
    }

}